package com.backend.utils.Http;

import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.util.StringUtils;

import java.io.IOException;
import java.util.Map;

public class HttpUtils {
    public static HttpConfig buildConfig(String url) {
        HttpConfig config = HttpConfig.custom().url(url).encoding("utf-8");
        return config;
    }

    public static HttpConfig buildConfig(String url, Map<String, Object> params) {
        HttpConfig config = HttpConfig.custom().url(url).map(params).encoding("utf-8");
        return config;
    }

    public static String HttpGetString(String url) {
        String result = null;     //get请求
        try {
            result = HttpClientUtil.get(buildConfig(url));
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static JsonNode HttpGetJsonNode(String url) {
        String result = null;     //get请求
        try {
            result = HttpClientUtil.get(buildConfig(url));
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNullOrEmpty(result)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = mapper.readTree(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonNode;
    }

    public static String HttpPostString(String url, Map<String, Object> params) {
        String result = null;     //get请求
        try {
            result = HttpClientUtil.post(buildConfig(url, params));
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static JsonNode HttpPostJsonNode(String url, Map<String, Object> params) {
        String result = null;     //get请求
        try {
            result = HttpClientUtil.post(buildConfig(url, params));
        } catch (HttpProcessException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNullOrEmpty(result)) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = null;
        try {
            jsonNode = mapper.readTree(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonNode;
    }
}
